﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MaxLeaf.Platform.Contract;
using MaxLeaf.Platform.DataContract;
using CommonsLib.DB;
using System.Transactions;
using System.Data.SqlClient;
using System.Data;
using System.Data.Common;
using System.Collections;

using System.Diagnostics;
using CommonsLib.Settings;
using CommonsLib.Utility;
using MaxLeaf.Platform.Functions;
using MaxLeaf.Platform.Commons;

namespace MaxLeaf.Platform.DALImplementation
{
    public class CategroyApproDAL : BaseDAL
    {
        public CategroyApproDataModel Confirm(DBAccess dbcon, CategroyApproDataModel model)
        {
            string strSQL = "";
            string strCategoryID = model.SCPCategorySeqNo.ToString();
            bool blnRightPerson = true;
            bool blnCurApproFinish = false; ///当前单据审核级别
            string strCurApproLevel = "";///此单据 当前审核到的级别 SCPBillApproStatus
            string strMaxApproLevel = "";///此类单据的最大审核级别  SCPCategoryApproLevel
            ArrayList arrOrigLevel =new ArrayList(10);//这个单据已经审核的人员 
            FinterIDType fBillType = (FinterIDType)model.FinterIDType;
            if (fBillType == FinterIDType.StoresReq)
            {
                #region 如果没有设置多级审核
                strMaxApproLevel = GetMaxApproLevel(dbcon, model, CvtFunc.ToInt ( model.CompanyID));
                if (CvtFunc.ToInt(strMaxApproLevel) == 0) //如果没有设置多级审核
                {
                    model.Success = true;
                    int intCompanyID = 0;
                    bool blnCurrentisChild=false;
                    using (DBAccess dbBaseaCon = new DBAccess(DataFunc.GetConnectionInfo(Const.DB_SCPBase)))
                    {
                        intCompanyID = mCompanyDAL.GetParentCompanyID(dbBaseaCon, CvtFunc.ToInt ( model.CompanyID));
                        if (intCompanyID > 0) blnCurrentisChild = true;
                    }
                    if (CvtFunc.ToInt(new CategroyApproDAL().GetMaxApproLevel(dbcon, model, intCompanyID)) == 0) // 如果没有设置多级审核则，则需要直接确认这个单据
                    {
                        intCompanyID = 0;
                    }
                    if (intCompanyID == 0 || blnCurrentisChild) //如果没有总公司,直接完成post
                    {
                        #region 1. 如果是最后一个级别的审核，则要写单据的Posted状态
                        strSQL = "UPDATE imStoresReqHdr Set Posted=1 WHERE FInterID='{0}'";
                        dbcon.ExecuteSql(string.Format(strSQL, model.BillFinterID));

                        string strOrigFinterID = dbcon.GetValue("Select OrigFinterID From imStoresReqHdr Where FInterID='" + model.BillFinterID + "'");
                        strSQL = "UPDATE imStoresReqHdr Set HeadPosted=1 WHERE FInterID='{0}'";
                        dbcon.ExecuteSql(string.Format(strSQL, strOrigFinterID));
                        model.Posted = true;
                        #endregion                        
                    }
                    model.Posted = true;
                    return model;
                }
                #endregion

                #region 1. 检查这个人在这一层中有没有审核权限  表：SCPCategoryApproUser

                #region 获得单据的当前已审核到的级别
                strSQL = @"Select isnull(max(ApproLevel),1) from SCPBillApproStatus where 
                           FBillID='{0}' and CompanyID='{1}' and CategorySeqNo='{2}' and FInterID='{3}'";
                strSQL = string.Format(strSQL, model.FinterIDType, model.CompanyID, model.SCPCategorySeqNo,model.BillFinterID);
                strCurApproLevel = CvtFunc.ToString(dbcon.GetValue(strSQL));
                #endregion
                if (strCurApproLevel == "") strCurApproLevel = "1";
                strSQL = @"Select userid From SCPCategoryApproUser where ApproLevel='{0}'
                          and FBillType='{1}' and UserID='{2}' and CompanyID='{3}' and CategorySeqNo='{4}'";
                strSQL = string.Format(strSQL, strCurApproLevel
                                                , model.FinterIDType
                                                , model.UserID
                                                , model.CompanyID
                                                , model.SCPCategorySeqNo
                                      );
                if (CvtFunc.ToLong(dbcon.GetValue(strSQL)) <= 0)  //如果没有权限
                {
                    model.Success = false;
                    blnCurApproFinish = true;
                    blnRightPerson = false;
                }
                #endregion

                // 检查这个单据现处的审核状态和已经参加审核的人员
                if (blnRightPerson)
                {
                    strSQL = @"Select top 1 * From SCPBillApproStatus where CompanyID='{0}' 
                           and FInterID='{1}' and CategorySeqNo='{2}' order by ApproLevel desc ";
                    strSQL = string.Format(strSQL, model.CompanyID, model.BillFinterID, model.SCPCategorySeqNo);
                    using (DbDataReader drOrigLevel = dbcon.GetDataFirstRow(strSQL))
                    {
                        if (!drOrigLevel.Read())
                        {
                            drOrigLevel.Close();
                            #region 更新SCPCategoryApproUser，单据审核状态表
                            strSQL = @"INSERT INTO SCPBillApproStatus ( ApproLevel,FBillID,FInterID,CategorySeqno,CompanyID,ApproUserID01 )
                                           VALUES ('{0}','{1}','{2}','{3}','{4}','{5}')";
                            strSQL = string.Format(strSQL, strCurApproLevel, model.FinterIDType, model.BillFinterID, model.SCPCategorySeqNo, model.CompanyID, model.UserID);
                            dbcon.ExecuteSql(strSQL);
                            arrOrigLevel.Add(model.UserID);

                            #region Add Blank Value into arrOrigLevel
                            arrOrigLevel.Add("");
                            arrOrigLevel.Add("");
                            arrOrigLevel.Add("");
                            arrOrigLevel.Add("");
                            arrOrigLevel.Add("");
                            arrOrigLevel.Add("");
                            arrOrigLevel.Add("");
                            arrOrigLevel.Add("");
                            arrOrigLevel.Add("");
                            #endregion

                            #region 更新出库申请单状态 --CurApproLevel
                            strSQL = @"UPDATE imStoresReqHdr Set CurApproLevel='{0}' WHERE FInterID='{1}' and CompanyID='{2}'  ";
                            strSQL = string.Format(strSQL, strCurApproLevel, model.BillFinterID, model.CompanyID);
                            dbcon.ExecuteSql(strSQL);

                            string strOrigFinterID = dbcon.GetValue("Select OrigFinterID From imStoresReqHdr Where FInterID='" + model.BillFinterID + "'");
                            strSQL = @"UPDATE imStoresReqHdr Set HeadCurApproLevel='{0}' WHERE FInterID='{1}' ";
                            strSQL = string.Format(strSQL, strCurApproLevel, CvtFunc.ToInt(strOrigFinterID));
                            dbcon.ExecuteSql(strSQL);
                            #endregion

                            AddCategoryApproHistory(dbcon, model, "Confirm", strCurApproLevel);
                            #endregion
                        }
                        else
                        {
                            if (ChkUserAlreadyInCurLevelPosted(drOrigLevel, model)) //如果这个user在这个层级中已经审核过
                            {
                                return model;
                            }
                            else  //如果这个user在这个层级中没有做过审核动作
                            {
                                #region 读取原来已审核的人员
                                arrOrigLevel.Add(CvtFunc.ToString(drOrigLevel["ApproUserID01"]));
                                arrOrigLevel.Add(CvtFunc.ToString(drOrigLevel["ApproUserID02"]));
                                arrOrigLevel.Add(CvtFunc.ToString(drOrigLevel["ApproUserID03"]));
                                arrOrigLevel.Add(CvtFunc.ToString(drOrigLevel["ApproUserID04"]));
                                arrOrigLevel.Add(CvtFunc.ToString(drOrigLevel["ApproUserID05"]));
                                arrOrigLevel.Add(CvtFunc.ToString(drOrigLevel["ApproUserID06"]));
                                arrOrigLevel.Add(CvtFunc.ToString(drOrigLevel["ApproUserID07"]));
                                arrOrigLevel.Add(CvtFunc.ToString(drOrigLevel["ApproUserID08"]));
                                arrOrigLevel.Add(CvtFunc.ToString(drOrigLevel["ApproUserID09"]));
                                arrOrigLevel.Add(CvtFunc.ToString(drOrigLevel["ApproUserID10"]));
                                #endregion
                                #region 更新SCPCategoryApproUser，单据审核状态表
                                string strFieldName = GetUserConfirmFieldInCurLevel(drOrigLevel, model);
                                string strRecID = CvtFunc.ToString(drOrigLevel["RecID"]);
                                drOrigLevel.Close();
                                if (CvtFunc.ToInt(strFieldName.Substring(strFieldName.Length - 2, 2)) >= 1
                                     && CvtFunc.ToInt(strFieldName.Substring(strFieldName.Length - 2, 2)) <= 10)
                                {
                                    arrOrigLevel[CvtFunc.ToInt(strFieldName.Substring(strFieldName.Length - 2, 2)) - 1] = model.UserID;
                                }
                                strSQL = "UPDATE SCPBillApproStatus Set {0} = {1} where RecID='{2}'";
                                strSQL = string.Format(strSQL, strFieldName, model.UserID, strRecID);
                                dbcon.ExecuteSql(strSQL);
                                AddCategoryApproHistory(dbcon, model, "Confirm", strCurApproLevel);
                                #endregion
                            }
                        }
                        strSQL = "select Operator from SCPCategoryApproLevel where CategorySeqNo='{0}' and CompanyID='{1}' and ApproLevel='{2}'";
                        string strOperator = dbcon.GetValue(string.Format(strSQL, model.SCPCategorySeqNo, model.CompanyID, strCurApproLevel));


                        if (strOperator == "OR")  //这一层只要一个人审核就可以
                        {
                            blnCurApproFinish = true;
                        }
                        else
                        {
                            #region  检查这一级中的所有人员是否已经审核完成
                            bool blnCheckAppro = true;
                            strSQL = @"select UserID from dbo.SCPCategoryApproUser  where CategorySeqNo='{0}' and CompanyID='{1}' and ApproLevel='{2}' AND UserID!='{3}'";
                            strSQL = string.Format(strSQL, model.SCPCategorySeqNo, model.CompanyID, strCurApproLevel, model.UserID);
                            using (DbDataReader drSetUserReader = dbcon.GetDataReader(strSQL))
                            {
                                while (drSetUserReader.Read())
                                {
                                    if (CvtFunc.ToString(drSetUserReader["UserID"]) == CvtFunc.ToString(arrOrigLevel[0])
                                        || CvtFunc.ToString(drSetUserReader["UserID"]) == CvtFunc.ToString(arrOrigLevel[1])
                                        || CvtFunc.ToString(drSetUserReader["UserID"]) == CvtFunc.ToString(arrOrigLevel[2])
                                        || CvtFunc.ToString(drSetUserReader["UserID"]) == CvtFunc.ToString(arrOrigLevel[3])
                                        || CvtFunc.ToString(drSetUserReader["UserID"]) == CvtFunc.ToString(arrOrigLevel[4])
                                        || CvtFunc.ToString(drSetUserReader["UserID"]) == CvtFunc.ToString(arrOrigLevel[5])
                                        || CvtFunc.ToString(drSetUserReader["UserID"]) == CvtFunc.ToString(arrOrigLevel[6])
                                        || CvtFunc.ToString(drSetUserReader["UserID"]) == CvtFunc.ToString(arrOrigLevel[7])
                                        || CvtFunc.ToString(drSetUserReader["UserID"]) == CvtFunc.ToString(arrOrigLevel[8])
                                        || CvtFunc.ToString(drSetUserReader["UserID"]) == CvtFunc.ToString(arrOrigLevel[9]))
                                    {

                                    }
                                    else
                                    {
                                        blnCheckAppro = false;
                                    }
                                }
                            }
                            blnCurApproFinish = blnCheckAppro;
                            #endregion
                        }
                    }
                }
                if (blnCurApproFinish) //检查如果是这一层全部审核完成了, 或者这一级不需要审核
                {
                    #region 检查如果是这一层全部审核完成了, 或者这一级不需要审核

                    strCurApproLevel = CvtFunc.ToString(CvtFunc.ToInt(strCurApproLevel) + 1);
                    if (CvtFunc.ToInt(strCurApproLevel) > CvtFunc.ToInt(strMaxApproLevel))
                    {
                        
                        #region 1. 如果是最后一个级别的审核，则要写单据的Posted状态
                        if (blnRightPerson || CvtFunc.ToInt(strMaxApproLevel) == 0)
                        {
                            strSQL = "UPDATE imStoresReqHdr Set Posted=1 WHERE FInterID='{0}'";
                            dbcon.ExecuteSql(string.Format(strSQL, model.BillFinterID));

                            string strOrigFinterID = dbcon.GetValue("Select OrigFinterID From imStoresReqHdr Where FInterID='" + model.BillFinterID + "'");
                            strSQL = "UPDATE imStoresReqHdr Set HeadPosted=1 WHERE FInterID='{0}'";
                            dbcon.ExecuteSql(string.Format(strSQL, strOrigFinterID));

                            model.Success = true;
                            model.Posted = true;
                            return model;
                        }
                        else
                        {
                            model.Success = false ;
                            return model;
                        }
                        #endregion
                    }
                    else
                    {
                        if (!blnRightPerson)  //如果没有权限
                        {
                            model.Success = false ;
                            return model;
                        }
                        else
                        {
                            #region 2. 如果不是最后一个级别，则要在新加一行，进入下一个级别审核
                            strSQL = @"INSERT INTO SCPBillApproStatus ( ApproLevel,FBillID,FInterID,CategorySeqNo,CompanyID )
                                           VALUES ('{0}','{1}','{2}','{3}','{4}')";
                            strSQL = string.Format(strSQL, strCurApproLevel, model.FinterIDType, model.BillFinterID, model.SCPCategorySeqNo, model.CompanyID);
                            dbcon.ExecuteSql(strSQL);

                            strSQL = @"UPDATE imStoresReqHdr Set CurApproLevel='{0}' WHERE FInterID='{1}' and CompanyID='{2}'  ";
                            strSQL = string.Format(strSQL, strCurApproLevel, model.BillFinterID, model.CompanyID);
                            dbcon.ExecuteSql(strSQL);

                            string strOrigFinterID = dbcon.GetValue("Select OrigFinterID From imStoresReqHdr Where FInterID='" + model.BillFinterID + "'");
                            strSQL = @"UPDATE imStoresReqHdr Set HeadCurApproLevel='{0}' WHERE FInterID='{1}' ";
                            strSQL = string.Format(strSQL, strCurApproLevel,strOrigFinterID);
                            dbcon.ExecuteSql(strSQL);
                            #endregion
                        }
                    }
                    #endregion
                }
                
                model.Success = true;
            }
            return model;
        }

        private void AddCategoryApproHistory(DBAccess dbcon, CategroyApproDataModel model,string strOperationType,string strCurApproLevel)
        {
            string strSQL = "";
            strSQL = @"INSERT INTO SCPApproHistory (FInterID, CurAppLevel,AppUserID,Operation,OperDate,ConfirmRemark)
                                            VALUES ('{0}','{1}','{2}','{3}','{4}','{5}')";
            strSQL = string.Format(strSQL , model.BillFinterID, strCurApproLevel, model.UserID, strOperationType, DateTime.Now,BaseFunc.SpecialCharDeal( model.ConfirmRemark));
            dbcon.ExecuteSql(strSQL); 
        }

        public CategroyApproDataModel UnConfirm(DBAccess dbcon, CategroyApproDataModel model)
        {
            string strSQL = "";
            string strCategoryID = model.SCPCategorySeqNo.ToString();
            string strCurApproLevel = "";///此单据 当前审核到的级别 SCPBillApproStatus
            string strMaxApproLevel = "";///此类单据的最大审核级别  SCPCategoryApproLevel
            FinterIDType fBillType = (FinterIDType)model.FinterIDType;
            if (fBillType == FinterIDType.StoresReq)
            {
                strSQL = @"Delete SCPBillApproStatus where FBillID='{0}' and FInterID='{1}' and CategorySeqNo='{2}' and CompanyID='{3}' ";
                strSQL = string.Format(strSQL, model.FinterIDType, model.BillFinterID, model.SCPCategorySeqNo, model.CompanyID);
                dbcon.ExecuteSql(strSQL);

                strSQL = @"Update imStoresReqHdr set DepartConfirmed=0,DocStatus=0, CurApproLevel='{0}' WHERE FInterID='{1}' and CompanyID='{2}'  ";
                strSQL = string.Format(strSQL, 0, model.BillFinterID, model.CompanyID);
                dbcon.ExecuteSql(strSQL);

                if ( CvtFunc.ToInt(model.BillFinterID) > 0)
                {
                    string strimStoresReqHdrFinterID = dbcon.GetValue("select FInterID from imStoresReqHdr where GroupFinterID=" + model.BillFinterID + "");
                    #region 如果是总公司unconfirm 分公司领用单
                    if (CvtFunc.ToInt(strimStoresReqHdrFinterID) > 0)
                    {
                        string strImimStoresReqHdr_OrigFInterID = CvtFunc.ToString(dbcon.GetValue("Select FInterID from imStoresReqHdr where GroupFinterID=" + strimStoresReqHdrFinterID + ""));
                        strSQL = "update imStoresReqDtl set Is_Delete=1 where HdrID = " + strimStoresReqHdrFinterID + "";
                        dbcon.ExecuteSql(strSQL);

                        strSQL = "update imStoresReqHdr set Is_Delete=1,DepartConfirmed=0,DocStatus=0 where GroupFinterID = " + model.BillFinterID + "";
                        dbcon.ExecuteSql(strSQL);

                        strSQL = "update imStoresReqHdr_Group set Is_Delete=1 where FInterID = " + model.BillFinterID + "";
                        dbcon.ExecuteSql(strSQL);

                        string strGroup_FinterID = model.BillFinterID;
                        model.BillFinterID = strImimStoresReqHdr_OrigFInterID;
                        #region 给子公司的领用申请单清理标志位
                        strSQL = @"Update imStoresReqHdr set DepartConfirmed=0,DocStatus=0, CurApproLevel='{0}' WHERE FInterID='{1}'  ";
                        strSQL = string.Format(strSQL, 0, model.BillFinterID);
                        dbcon.ExecuteSql(strSQL);
                        #endregion
                        #region 给子公司的领用申请单写审核历史记录                     
                        AddCategoryApproHistory(dbcon, model, "UnCofirm", "0");
                        #endregion
                        model.BillFinterID = strGroup_FinterID;
                    }
                    #endregion
                }
                AddCategoryApproHistory(dbcon, model, "UnCofirm", "0");
            }
            model.Success = true;
            return model; 
        }



        /// <summary>
        /// 获取这个领用申请单的是不是需要多级审核， 如果返回是“0”，则是没有设置多级审核
        /// </summary>
        public string  GetMaxApproLevel(DBAccess dbcon, CategroyApproDataModel model, int intCompanyID)
        {
            using (DBAccess dbBase = new DBAccess(DataFunc.GetConnectionInfo(Const.DB_SCPBase)))
            {
                bool blnActive = CvtFunc.ToBoolean(dbBase.GetValue("select Is_Active from SCPCategory where SCPCategorySeqNo =@SCPCategorySeqNo and CompanyID=@CompanyID",
                     new SqlParameter[] { new SqlParameter(  "@SCPCategorySeqNo",   model.SCPCategorySeqNo.ToString ()),
                                      new SqlParameter(  "@CompanyID", intCompanyID.ToString ())}));
                if (blnActive == false) return "0";
            }
            string strMaxApproLevel = "";
            string strSQL = "select isnull(max(ApproLevel),0) as MaxLevel From SCPCategoryApproLevel where CategorySeqNo='{0}' and CompanyID='{1}' ";
            strMaxApproLevel = CvtFunc.ToString(dbcon.GetValue(string.Format(strSQL, model.SCPCategorySeqNo, intCompanyID)));
            return strMaxApproLevel;
        }


        /// <summary>
        /// 检查这个user是否已经在这一级审核过，如果在这一级已经审核过，则跳过
        /// </summary>
        /// <returns></returns>
        private bool ChkUserAlreadyInCurLevelPosted(DbDataReader drCurRead, CategroyApproDataModel model)
        {
            if (CvtFunc.ToString(drCurRead["ApproUserID01"]).Equals(model.UserID)) { return true; }
            if (CvtFunc.ToString(drCurRead["ApproUserID02"]).Equals(model.UserID)) { return true; }
            if (CvtFunc.ToString(drCurRead["ApproUserID03"]).Equals(model.UserID)) { return true; }
            if (CvtFunc.ToString(drCurRead["ApproUserID04"]).Equals(model.UserID)) { return true; }
            if (CvtFunc.ToString(drCurRead["ApproUserID05"]).Equals(model.UserID)) { return true; }
            if (CvtFunc.ToString(drCurRead["ApproUserID06"]).Equals(model.UserID)) { return true; }
            if (CvtFunc.ToString(drCurRead["ApproUserID07"]).Equals(model.UserID)) { return true; }
            if (CvtFunc.ToString(drCurRead["ApproUserID08"]).Equals(model.UserID)) { return true; }
            if (CvtFunc.ToString(drCurRead["ApproUserID09"]).Equals(model.UserID)) { return true; }
            if (CvtFunc.ToString(drCurRead["ApproUserID10"]).Equals(model.UserID)) { return true; }
            return false;
        }

        private string GetUserConfirmFieldInCurLevel(DbDataReader drCurRead, CategroyApproDataModel model)
        {
            if (string.IsNullOrEmpty(CvtFunc.ToString(drCurRead["ApproUserID01"])) || CvtFunc.ToString(drCurRead["ApproUserID01"]) == "0") { return "ApproUserID01"; }
            if (string.IsNullOrEmpty(CvtFunc.ToString(drCurRead["ApproUserID02"])) || CvtFunc.ToString(drCurRead["ApproUserID02"]) == "0") { return "ApproUserID02"; }
            if (string.IsNullOrEmpty(CvtFunc.ToString(drCurRead["ApproUserID03"])) || CvtFunc.ToString(drCurRead["ApproUserID03"]) == "0") { return "ApproUserID03"; }
            if (string.IsNullOrEmpty(CvtFunc.ToString(drCurRead["ApproUserID04"])) || CvtFunc.ToString(drCurRead["ApproUserID04"]) == "0") { return "ApproUserID04"; }
            if (string.IsNullOrEmpty(CvtFunc.ToString(drCurRead["ApproUserID05"])) || CvtFunc.ToString(drCurRead["ApproUserID05"]) == "0") { return "ApproUserID05"; }
            if (string.IsNullOrEmpty(CvtFunc.ToString(drCurRead["ApproUserID06"])) || CvtFunc.ToString(drCurRead["ApproUserID06"]) == "0") { return "ApproUserID06"; }
            if (string.IsNullOrEmpty(CvtFunc.ToString(drCurRead["ApproUserID07"])) || CvtFunc.ToString(drCurRead["ApproUserID07"]) == "0") { return "ApproUserID07"; }
            if (string.IsNullOrEmpty(CvtFunc.ToString(drCurRead["ApproUserID08"])) || CvtFunc.ToString(drCurRead["ApproUserID08"]) == "0") { return "ApproUserID08"; }
            if (string.IsNullOrEmpty(CvtFunc.ToString(drCurRead["ApproUserID09"])) || CvtFunc.ToString(drCurRead["ApproUserID09"]) == "0") { return "ApproUserID09"; }
            if (string.IsNullOrEmpty(CvtFunc.ToString(drCurRead["ApproUserID10"])) || CvtFunc.ToString(drCurRead["ApproUserID10"]) == "0") { return "ApproUserID10"; }
            return "";
        }

        #region 部门审核
        public CategroyApproDataModel DepartApproval_StoreReq(DBAccess dbcon, CategroyApproDataModel model)
        {
            string strSQL = "update imStoresReqHdr set DepartConfirmed=1,CurApproLevel=1 WHERE FInterID=@FInterID and CompanyID=@CompanyID";
            dbcon.ExecuteSql(strSQL, new SqlParameter[]{ new SqlParameter("@FInterID", model.BillFinterID)
                                                         ,new SqlParameter ("@CompanyID" , model.CompanyID)});
            model.Success = true;

            AddCategoryApproHistory(dbcon, model, "DepartConfirm", "0");
            return model;
        }
        #endregion
    }
}
